package cn.tedu.boot41.controller;

import cn.tedu.boot41.mapper.UserMapper;
import cn.tedu.boot41.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    UserMapper mapper;

    @RequestMapping("/check")
    @ResponseBody
    public int check(String username){

        User user = mapper.selectByUsername(username);
        if (user != null){
            return 2;
        }
        return 1;
    }

    @RequestMapping("/reg")
    @ResponseBody
    public int reg(User user){
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null){
            return 2;   //代表用户已存在
        }

        //把数据保存在user表中
        mapper.insert(user);
        return 1;  //注册成功
    }

    @RequestMapping("/login")
    @ResponseBody
    public int login(User user, String rem, HttpServletResponse response, HttpSession session){

        User u = mapper.selectByUsername(user.getUsername());
        if (u == null){ //判断用户是否存在 //不存在则返回2，存在则判断密码
            return 2;
        }
        if (u.getPassword().equals(user.getPassword())){ //判断输入的密码和数据库中查询的密码是否一致
            /*
                登录成功时把当前登录的用户信息保存到会话对象中
                保存到Session里面的数据可以
             */
            session.setAttribute("u",u);
            if (rem != null){
                Cookie c1 = new Cookie("username",user.getUsername());
                Cookie c2 = new Cookie("password", user.getPassword());
                //保存一个月
                c1.setMaxAge(60*60*24*30);
                response.addCookie(c1);
                response.addCookie(c2);
            }

            return 1; //一致则返回登录成功
        }
        return 3; //密码错误

    }


    @RequestMapping("/currentUser")
    @ResponseBody
    public User currentUser(HttpSession session){
        //取出登录成功时保存的用户对象
        return (User) session.getAttribute("u");
    }

    @RequestMapping("/logout")
    @ResponseBody
    public void logout(HttpSession session){
        //删除登录成功时保存的用户对象
        session.removeAttribute("u");
    }

}
